import { getDocument, GlobalWorkerOptions } from 'pdf';
import {getContext} from './context.js';
GlobalWorkerOptions.workerSrc = '/module/pdf.worker.min.mjs';

export async function convertPdfToImage(file) {
    const context = getContext();
    const log = (value) => context.uploadStatus = value;
    log('开始读取PDF文件');
    const fileArrayBuffer = await readFile(file);
    log('PDF文件读取完毕');
    const pdf = await getDocument({ data: fileArrayBuffer }).promise;
    log('获取PDF文档完毕');
    const tasks = [];
    const images = [];
    let scale = 1.5;
    for (let i = 0; i < pdf.numPages; i++) {
        tasks.push(createTask(i));
    }
    async function createTask(i) {
        const currentPage = i + 1;
        log(`正在读取PDF文件: 第${currentPage}页`);
        const page = await pdf.getPage(currentPage);
        const viewport = page.getViewport({ scale });
        const canvas = document.createElement('canvas');
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        const ctx = canvas.getContext('2d');
        const renderContext = { canvasContext: ctx, viewport: viewport };
        log(`PDF读取完毕, 开始把PDF转换成PNG: ${file.name}，第${currentPage}页`);
        await page.render(renderContext).promise;
        const blob = await canvasToBlob(canvas);
        const pdfFileName = file.name.replace('.pdf', '');
        const imgFileName = pdfFileName + `_page_${currentPage}.png`;
        const imageFile = new File([blob], imgFileName, {
            type: 'image/png',
            lastModified: file.lastModified,
        });
        log('成功生成图片文件：' + imageFile.name);
        images.push(imageFile);
    }
    await Promise.all(tasks);
    log('所有PDF图片文件生成完毕');
    return images;
}

function readFile(file) {
    return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            resolve(new Uint8Array(e.target.result));
        };
        reader.readAsArrayBuffer(file);
    });
}

function canvasToBlob(canvas) {
    return new Promise((resolve) => {
        canvas.toBlob((blob) => {
            resolve(blob);
        });
    });
}
